package com.kk.xhr.model.service.impl;

import com.kk.xhr.common.pojo.BinaryEnum;
import com.kk.xhr.model.dao.WorkTimeDynamicSqlSupport;
import com.kk.xhr.model.dao.WorkTimeMapper;
import com.kk.xhr.model.dto.WorkTimeDTO;
import com.kk.xhr.model.entity.WorkTime;
import com.kk.xhr.model.service.IWorkTimeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.Optional;

import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;

/**
 * 工作时间服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/3/1
 * @since 1.0.0
 */
@Repository
@RequiredArgsConstructor
public class WorkTimeServiceImpl implements IWorkTimeService {
    private final WorkTimeMapper workTimeMapper;

    /**
     * {@inheritDoc}
     */
    @Override
    public Optional<WorkTimeDTO> queryLatest() {
        return workTimeMapper.selectOne(dsl -> dsl
            .where(WorkTimeDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue()))
            .orderBy(WorkTimeDynamicSqlSupport.id.descending()).limit(1))
            .map(entity -> WorkTimeDTO.builder()
                .id(entity.getId())
                .earlyBegin(entity.getEarlyBegin())
                .earlyEnd(entity.getEarlyEnd())
                .lateBegin(entity.getLateBegin())
                .lateEnd(entity.getLateEnd())
                .duration(entity.getDuration())
                .flexDuration(entity.getFlexDuration())
                .status(BinaryEnum.from(entity.getStatus()))
                .build());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void modify(WorkTime workTime) {
        workTimeMapper.updateByPrimaryKeySelective(workTime);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Optional<WorkTime> query() {
        return workTimeMapper.selectOne(dsl -> dsl
            .where(WorkTimeDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue()))
            .orderBy(WorkTimeDynamicSqlSupport.id.descending()).limit(1));
    }
}
